package com.xiumu.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xiumu.common.core.constants.XiuMuConst;
import com.xiumu.common.core.utils.IncreaseUtils;
import com.xiumu.config.XiuMuProperties;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求追踪拦截
 * 给每一个请求设置一个 traceId
 *
 * @Author XiuMu
 * @Date 2023/2/8 11:12
 **/
public class TraceInterceptor implements HandlerInterceptor {

    /**
     * 配置的实例ID
     */
    private final XiuMuProperties xiuMuProperties;

    public TraceInterceptor(XiuMuProperties xiuMuProperties) {
        this.xiuMuProperties = xiuMuProperties;
    }

    /**
     * 生成 traceID
     * 实例 ID.当前时间戳.自增序列.当前线程 ID
     * 实例 ID 是给每一个服务自定义的一个 ID，多实例情况下根据这个实例 ID 判断是哪个实例的日志
     *
     * @param request 请求体，用来获取IP
     */
    private String createTraceId(HttpServletRequest request){
        return xiuMuProperties.getInstanceId() + StrUtil.DOT +
                System.currentTimeMillis() + StrUtil.DOT +
                IncreaseUtils.getIncreaseNum() + StrUtil.DOT +
                Thread.currentThread().getId();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String traceId = createTraceId(request);
        MDC.put(XiuMuConst.TRACE_ID, traceId);
        response.addHeader(XiuMuConst.TRACE_ID, traceId);
        return true;
    }
}
